<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => '未登录']);
    exit;
}

// 检查请求方法
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '无效的请求方法']);
    exit;
}

// 简单的频率限制（防止暴力破解）
$rate_limit_key = 'password_change_' . $_SESSION['user_id'] . '_' . $_SERVER['REMOTE_ADDR'];
$rate_limit_file = sys_get_temp_dir() . '/' . md5($rate_limit_key) . '.tmp';

if (file_exists($rate_limit_file)) {
    $last_attempt = (int)file_get_contents($rate_limit_file);
    if (time() - $last_attempt < 60) { // 1分钟内只能尝试一次
        echo json_encode(['success' => false, 'message' => '操作过于频繁，请稍后再试']);
        exit;
    }
}

file_put_contents($rate_limit_file, time());

// 获取POST数据
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    echo json_encode(['success' => false, 'message' => '无效的请求数据']);
    exit;
}

// 过滤和验证输入
$old_password = trim($input['old_password'] ?? '');
$new_password = trim($input['new_password'] ?? '');
$confirm_password = trim($input['confirm_password'] ?? '');

// 验证输入长度
if (strlen($old_password) > 100 || strlen($new_password) > 100 || strlen($confirm_password) > 100) {
    echo json_encode(['success' => false, 'message' => '输入内容过长']);
    exit;
}

// 验证输入
if (empty($old_password) || empty($new_password) || empty($confirm_password)) {
    echo json_encode(['success' => false, 'message' => '所有字段都不能为空']);
    exit;
}

// 验证新密码确认
if ($new_password !== $confirm_password) {
    echo json_encode(['success' => false, 'message' => '两次输入的新密码不一致']);
    exit;
}

// 检查是否包含非法字符
if (!mb_check_encoding($old_password, 'UTF-8') || !mb_check_encoding($new_password, 'UTF-8')) {
    echo json_encode(['success' => false, 'message' => '密码包含非法字符']);
    exit;
}

try {
    // 调用修改密码函数
    $user_id = $_SESSION['user_id'];
    $result = changeUserPassword($user_id, $old_password, $new_password);
    
    // 如果修改成功，清除频率限制
    if ($result['success'] && file_exists($rate_limit_file)) {
        unlink($rate_limit_file);
    }
    
    echo json_encode($result);
    
} catch (Exception $e) {
    // 记录错误日志
    error_log("密码修改错误: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => '系统错误，请稍后重试']);
}
?>
